import React, { useState } from 'react';
import {
  Select,
  Avatar,
  Space,
  Typography,
  Tag,
  Dropdown,
  Button,
  Divider,
  Modal,
  List,
  Card,
  Tooltip,
  message,
} from 'antd';
import {
  SwapOutlined,
  HomeOutlined,
  TeamOutlined,
  SettingOutlined,
  CheckCircleOutlined,
} from '@ant-design/icons';
import { useTenantContext, useTenantPermissions } from '../../stores/tenant';
import { Tenant } from '../../types/tenant';

const { Text } = Typography;
const { Option } = Select;

interface TenantSelectorProps {
  style?: React.CSSProperties;
  placement?: 'header' | 'sidebar';
  showTenantInfo?: boolean;
}

const TenantSelector: React.FC<TenantSelectorProps> = ({
  style,
  placement = 'header',
  showTenantInfo = true,
}) => {
  const {
    currentTenant,
    accessibleTenants,
    isLoading,
    switchTenant,
    hasMultipleTenants,
  } = useTenantContext();

  const { isSuperAdmin } = useTenantPermissions();

  const [switchModalVisible, setSwitchModalVisible] = useState(false);
  const [switching, setSwitching] = useState(false);

  // 处理租户切换
  const handleTenantSwitch = async (tenantId: string) => {
    if (tenantId === currentTenant?.id) {
      message.info('已经在当前租户中');
      return;
    }

    setSwitching(true);
    try {
      await switchTenant(tenantId);
      message.success('切换租户成功');
      setSwitchModalVisible(false);
      
      // 可以触发页面刷新或重新加载数据
      window.location.reload();
    } catch (error) {
      message.error('切换租户失败');
      console.error('租户切换失败:', error);
    } finally {
      setSwitching(false);
    }
  };

  // 获取租户状态标签
  const getTenantStatusTag = (tenant: Tenant) => {
    const statusConfig = {
      active: { color: 'green', text: '正常' },
      inactive: { color: 'default', text: '停用' },
      suspended: { color: 'orange', text: '暂停' },
      expired: { color: 'red', text: '过期' },
    };

    const config = statusConfig[tenant.status];
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 获取订阅计划标签
  const getSubscriptionTag = (tenant: Tenant) => {
    const planConfig = {
      free: { color: 'default', text: '免费版' },
      basic: { color: 'blue', text: '基础版' },
      professional: { color: 'purple', text: '专业版' },
      enterprise: { color: 'gold', text: '企业版' },
    };

    const config = planConfig[tenant.subscription.plan];
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 渲染租户信息卡片
  const renderTenantCard = (tenant: Tenant, isCurrent: boolean = false) => (
    <Card
      size="small"
      style={{
        marginBottom: 8,
        border: isCurrent ? '2px solid #1890ff' : '1px solid #d9d9d9',
        background: isCurrent ? '#f0f9ff' : '#ffffff',
      }}
      bodyStyle={{ padding: '12px 16px' }}
    >
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <Avatar
          size={40}
          src={tenant.logo}
          style={{ backgroundColor: '#1890ff', flexShrink: 0 }}
        >
          {tenant.name.charAt(0)}
        </Avatar>
        
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
            <Text strong style={{ fontSize: 14 }}>{tenant.name}</Text>
            {isCurrent && <CheckCircleOutlined style={{ color: '#52c41a' }} />}
          </div>
          
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
            {getTenantStatusTag(tenant)}
            {getSubscriptionTag(tenant)}
            <Tag color="blue">
              <TeamOutlined style={{ marginRight: 2 }} />
              {tenant.quota.currentUsers}人
            </Tag>
          </div>
          
          <Text type="secondary" style={{ fontSize: 12 }}>
            {tenant.description || tenant.domain || '暂无描述'}
          </Text>
        </div>

        {!isCurrent && (
          <Button
            type="primary"
            size="small"
            loading={switching}
            onClick={() => handleTenantSwitch(tenant.id)}
          >
            切换
          </Button>
        )}
      </div>
    </Card>
  );

  // 简单模式：下拉选择
  const renderSimpleSelector = () => (
    <Select
      value={currentTenant?.id}
      style={{ minWidth: 200, ...style }}
      placeholder="选择租户"
      loading={isLoading}
      onChange={handleTenantSwitch}
      optionLabelProp="label"
    >
      {accessibleTenants.map(tenant => (
        <Option key={tenant.id} value={tenant.id} label={tenant.name}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <Avatar size={24} src={tenant.logo}>
              {tenant.name.charAt(0)}
            </Avatar>
            <div>
              <div>{tenant.name}</div>
              <Text type="secondary" style={{ fontSize: 12 }}>
                {getSubscriptionTag(tenant)}
              </Text>
            </div>
          </div>
        </Option>
      ))}
    </Select>
  );

  // 高级模式：租户信息展示
  const renderAdvancedSelector = () => {
    const dropdownMenu = (
      <div style={{ width: 320, padding: 8 }}>
        {/* 当前租户信息 */}
        {currentTenant && (
          <>
            <div style={{ padding: '8px 12px' }}>
              <Text type="secondary" style={{ fontSize: 12 }}>当前租户</Text>
            </div>
            {renderTenantCard(currentTenant, true)}
            
            {hasMultipleTenants && <Divider style={{ margin: '8px 0' }} />}
          </>
        )}

        {/* 其他可访问租户 */}
        {hasMultipleTenants && (
          <>
            <div style={{ padding: '8px 12px' }}>
              <Text type="secondary" style={{ fontSize: 12 }}>其他租户</Text>
            </div>
            {accessibleTenants
              .filter(tenant => tenant.id !== currentTenant?.id)
              .slice(0, 3)
              .map(tenant => renderTenantCard(tenant))
            }

            {accessibleTenants.length > 4 && (
              <div style={{ textAlign: 'center', padding: '8px' }}>
                <Button
                  type="link"
                  size="small"
                  onClick={() => setSwitchModalVisible(true)}
                >
                  查看全部租户 ({accessibleTenants.length})
                </Button>
              </div>
            )}

            <Divider style={{ margin: '8px 0' }} />
            
            <div style={{ padding: '4px 8px' }}>
              <Button
                type="text"
                size="small"
                block
                icon={<SwapOutlined />}
                onClick={() => setSwitchModalVisible(true)}
              >
                管理租户
              </Button>
            </div>
          </>
        )}
      </div>
    );

    return (
      <Dropdown
        overlay={dropdownMenu}
        trigger={['click']}
        placement="bottomLeft"
      >
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            gap: 8,
            padding: '4px 12px',
            borderRadius: 6,
            cursor: 'pointer',
            background: '#fafafa',
            border: '1px solid #d9d9d9',
            ...style,
          }}
        >
          <Avatar
            size={24}
            src={currentTenant?.logo}
            style={{ backgroundColor: '#1890ff' }}
          >
            {currentTenant?.name?.charAt(0) || 'T'}
          </Avatar>
          
          {showTenantInfo && (
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 500 }}>
                {currentTenant?.name || '未选择租户'}
              </div>
              {currentTenant && (
                <div style={{ fontSize: 12, color: '#8c8c8c' }}>
                  {getSubscriptionTag(currentTenant)}
                                     {isSuperAdmin && <Tag color="red">超管</Tag>}
                </div>
              )}
            </div>
          )}
          
          <SwapOutlined style={{ color: '#8c8c8c' }} />
        </div>
      </Dropdown>
    );
  };

  // 租户切换模态框
  const renderSwitchModal = () => (
    <Modal
      title={
        <Space>
          <SwapOutlined />
          <span>切换租户</span>
        </Space>
      }
      open={switchModalVisible}
      onCancel={() => setSwitchModalVisible(false)}
      footer={null}
      width={600}
    >
      <div style={{ maxHeight: 500, overflow: 'auto' }}>
        <List
          dataSource={accessibleTenants}
          renderItem={(tenant) => (
            <List.Item style={{ padding: 0, marginBottom: 8 }}>
              {renderTenantCard(tenant, tenant.id === currentTenant?.id)}
            </List.Item>
          )}
        />
      </div>
      
      {isSuperAdmin && (
        <>
          <Divider />
          <div style={{ textAlign: 'center' }}>
            <Space>
              <Button
                icon={<SettingOutlined />}
                onClick={() => {
                  // 跳转到租户管理页面
                  window.open('/admin/tenants', '_blank');
                }}
              >
                租户管理
              </Button>
              <Button
                icon={<HomeOutlined />}
                onClick={() => {
                  // 切换到平台管理视图
                  console.log('切换到平台管理视图');
                }}
              >
                平台管理
              </Button>
            </Space>
          </div>
        </>
      )}
    </Modal>
  );

  // 如果没有租户或只有一个租户，不显示选择器
  if (!currentTenant && !hasMultipleTenants) {
    return null;
  }

  return (
    <>
      {placement === 'header' && hasMultipleTenants
        ? renderAdvancedSelector()
        : renderSimpleSelector()
      }
      {renderSwitchModal()}
    </>
  );
};

export default TenantSelector; 